<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="search">
        <el-form-item v-haspermi="['bxy:manager:search']" :label="$t('settings.roleName')">
          <el-input
            v-model="search.roleName"
            :placeholder="$t('settings.inputName')"
            :maxlength="50"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-haspermi="['bxy:manager:search']"
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="refreshList"
          >{{ $t('common.search') }}</el-button>
        </el-form-item>
        <el-button
          v-haspermi="['bxy:manager:add']"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="addRole"
        >{{ $t('common.newAdd') }}</el-button>
      </el-form>
    </div>
    <el-table :data="result.data" border @sort-change="handleSortChange">
      <el-table-column
        property="name"
        :label="$t('settings.name')"
        align="center"
        width="200px"
      />
      <el-table-column
        property="description"
        :label="$t('settings.description')"
        align="center"
      />
      <el-table-column
        :label="$t('common.operate')"
        align="center"
        width="200px"
      >
        <template slot-scope="scope">
          <el-button v-haspermi="['bxy:manager:edit']" type="primary" plain size="mini" @click="editRole(scope.row)">
            {{ $t('common.editor') }}
          </el-button>
          <el-button
            v-haspermi="['bxy:manager:delete']"
            type="danger"
            plain
            size="mini"
            @click.native.prevent="deleteRole(scope.row)"
          >
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="result.totalCount > 0"
      :total="result.totalCount"
      :page.sync="search.page"
      :limit.sync="search.size"
      @pagination="pagination"
    />
    <div class="manager-form">
      <el-dialog :title="title" :visible.sync="formVisible" width="600px" :before-close="reset">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item :label="$t('settings.roleName')" prop="name">
            <el-input
              v-model="form.name"
            />
          </el-form-item>
          <el-form-item label="权限字符" prop="roleKey">
            <el-input
              v-model="form.roleKey"
            />
          </el-form-item>

          <el-form-item :label="$t('settings.authoritySelect')">
            <el-checkbox v-model="menuExpand" @change="checkedTreeExpand($event)">展开/折叠</el-checkbox>
            <el-checkbox v-model="menuNodeAll" @change="checkedTreeNodeAll($event)">全选/全不选</el-checkbox>
            <el-checkbox v-model="menuStrictly" @change="checkedTreeConnect($event)">父子联动</el-checkbox>
            <div class="depts-tree">
              <el-tree
                ref="rights"
                :data="patterns"
                :props="patternProps"
                node-key="id"
                show-checkbox
                :default-checked-keys="defaultCheckedKeys"
                :check-strictly="!menuStrictly"
              />
            </div>
          </el-form-item>

          <el-form-item :label="$t('settings.description')">
            <el-input
              v-model="form.description"
              type="textarea"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('form')">{{
              $t('common.submit')
            }}</el-button>
            <el-button @click="formVisible = false">{{ $t('common.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import * as settings from '@/api/settings';
import Pagination from '@/components/Pagination';
export default {
  name: 'ManagerRoleList',
  components: { Pagination },
  data() {
    return {
      search: {
        roleName: null,
        page: 1,
        size: 10,
      },
      result: {
        code: 0,
        msg: '',
        data: [],
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
      },
      currentPersonInfo: {},
      menuStrictly: true,
      menuNodeAll: false,
      menuExpand: false,
      patterns: [],
      patternProps: {
        label: 'label',
        children: 'children',
      },
      exrendKeys: [1],
      defaultCheckedKeys: [],
      form: {
        id: null,
        name: null,
        menus: [],
        description: null,
        roleKey: null,
      },
      formVisible: false,
      title: '',
      rules: {
        name: [
          {
            required: true,
            message: this.$t('settings.inputName'),
            trigger: 'blur',
          },
        ],
        roleKey: [{
          required: true,
          message: '请输入权限字符',
          trigger: 'blur',
        }],
      },
    };
  },
  computed: {
    ...mapGetters(['isSuperman']),
  },
  created() {
    this.getRoleList();
    this.loadNode();
  },
  methods: {
    /**
     * 重新获取管理员角色列表
     */
    refreshList() {
      this.search.page = 1;
      this.getRoleList();
    },
    /**
     * 获取管理员角色列表
     */
    async getRoleList() {
      const res = await settings.getRoles(this.search);
      this.result = res;
      this.result.totalCount = Number(res.headers['x-total-count']);
      this.getListByPageOne();
    },
    /**
     * 防止分页传参错误问题导致暂无数据
     */
    getListByPageOne() {
      if (
        this.search.page !== 1 &&
        this.result.totalCount / this.search.size <= this.search.page - 1
      ) {
        this.search.page = 1;
        this.getRoleList();
      }
    },
    /**
     * 根据表格的排序条件发生变化触发请求
     * @param {Object} row 表格栏目对象（包含每条栏目的数据和属性）
     */
    handleSortChange(row) {
      this.search.page = 1;
      this.search.sortfiled = row.prop;
      this.search.sorttype = row.order === 'descending' ? 'desc' : 'asc';
      this.getRoleList();
    },
    /**
     * 添加管理员角色
     */
    addRole() {
      this.title = '新增角色';
      this.formVisible = true;
      this.menuStrictly = true;
      this.menuNodeAll = false;
      this.menuExpand = false;
    },
    /**
     * 编辑管理员角色
     * @param {Object} row 表格栏目对象（包含每条栏目的数据和属性）
     */
    editRole(row) {
      const { name, id, roleKey, description } = row;
      this.title = '编辑角色';
      this.formVisible = true;
      this.form.id = id;
      this.form.name = name;
      this.form.roleKey = roleKey;
      this.form.description = description;
      /**
       * eltree回显
       */
      settings.roleMenuTreeSelect(row.id).then(res => {
        this.$nextTick(() => {
          res.data.checkedKeys.forEach(el => {
            const node = this.$refs.rights.getNode(el);
            if (node.isLeaf) {
              this.$refs.rights.setChecked(node, true);
            }
          });
        });
      })
        .catch(err => {
          console.log(err);
        });
    },
    /**
     * 删除管理员角色
     * @param {Object} row 表格栏目对象（包含每条栏目的数据和属性）
     */
    deleteRole(row) {
      this.$confirm(this.$t('settings.tips'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.ok'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      })
        .then(() => {
          settings.deleteRoleInfo(row.id).then(res => {
            this.$message({
              message: this.$t('settings.deleteSuccess'),
              type: 'success',
            });
            this.getRoleList();
          });
        })
        .catch(() => {});
    },
    /**
     * 管理员角色状态格式化
     * @param {Number} cellValue table 单元格数据值 详细参数解释参考以下链接：
     * https://element.eleme.cn/#/zh-CN/component/table
     */
    formatStatus(row, column, cellValue, index) {
      if (cellValue) {
        switch (cellValue) {
          case 1:
            return this.$t('common.normal');
          case 2:
            return this.$t('common.disabled');
          default:
            return this.$t('common.other');
        }
      } else {
        return '';
      }
    },
    /**
     * 模版分页
     */
    pagination() {
      this.getRoleList();
    },

    handleSizeChange(val) {
      this.search.size = val;
      this.getRoleList();
    },

    handleCurrentChange(val) {
      this.search.page = val;
      this.getRoleList();
    },
    /**
     * 获取权限数据
     */
    loadNode() {
      settings
        .treeSelect()
        .then(res => {
          this.patterns = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    /**
     * 保存管理员角色
     */
    submitForm() {
      const getCheckedKeys = this.$refs['rights'].getCheckedKeys();// 选中的菜单节点
      const halfCheckedKeys = this.$refs['rights'].getHalfCheckedKeys(); // 半选中的菜单节点
      this.form.menus = JSON.stringify(getCheckedKeys.concat(halfCheckedKeys));
      this.$refs['form'].validate(valid => {
        if (valid) {
          settings.saveRole(this.form, this.form.id).then(result => {
            this.$message({
              message: this.$t('common.operateSuccess'),
              type: 'success',
            });
            this.formVisible = false;
            this.getRoleList();
          });
        } else {
          this.$message({
            message: this.$t('settings.formError'),
            type: 'error',
          });
        }
      });
    },
    /**
     * 展开/折叠
     * */
    checkedTreeExpand(value) {
      const treeList = this.patterns;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.rights.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    /**
     * 全选/全不选
     * */
    checkedTreeNodeAll(value) {
      this.$refs.rights.setCheckedNodes(value ? this.patterns : []);
    },

    checkedTreeConnect(value) {
      this.menuStrictly = !!value;
    },

    reset() {
      this.form = {
        id: null,
        name: null,
        menus: [],
        description: null,
        roleKey: null,
      };
      this.formVisible = false;
      this.$refs.form.clearValidate();
      this.$nextTick(() => {
        this.$refs.rights.setCheckedKeys([]);
      });
    },
  },
};
</script>

<style scoped>
.filter {
  display: flex;
  margin-left: 15px;
  margin-top: 15px;
  color: #333;
  font-size: 14px;
}
.filter-tit {
  display: inline-block;
  height: 40px;
  line-height: 40px;
  vertical-align: top;
  color: #999;
}
.department {
  margin-left: 15px;
}
.el-input {
  width: 250px;
}
.button {
  margin-left: 15px;
}
.table {
  width: 100%;
  margin-left: 10px;
  margin-top: 20px;
}
.text-col {
  font-size: 0;
  margin-bottom: 20px;
}
.text-key {
  display: inline-block;
  vertical-align: top;
  margin-right: 10px;
  font-size: 13px;
  color: #9d9d9d;
}
.text-value {
  display: inline-block;
  vertical-align: top;
  max-width: 150px;
  font-size: 13px;
  color: #212121;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.text-value-long {
  max-width: 100%;
  margin-top: 10px;
  font-size: 13px;
  color: #212121;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.manager-form {
  padding: 15px;
}
.depts-tree {
  display: inline-block;
  min-width: 200px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>
